package netty.server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TimeServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            log.info("receive data1: {}", msg);
            final ByteBuf byteBuf = (ByteBuf) msg;
            log.info("receive data2: {}", byteBuf.readLong());

            // byteBuf.release();
        } finally {
             ReferenceCountUtil.release(msg);
        }
    }

    private void sendTime(ChannelHandlerContext ctx) {
        final long time = System.currentTimeMillis();
        log.info("send time: {}", time);

        final ByteBuf buffer = ctx.alloc().buffer(8);
        buffer.writeLong(time);
        final ChannelFuture future = ctx.writeAndFlush(buffer);

//        future.addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        sendTime(ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        // cause.printStackTrace();
        log.error("", cause);
        ctx.close();
    }
}